<?php

namespace App\Http\Controllers;

use App\Models\ClaimProject;
use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ClaimProjectController extends Controller
{
    public function show(Request $request, $id) {
        $node = ClaimProject::findOrFail($id);
        $node->load('org');
        $data = $node->toArray();
        return $this->returnJSON($data, 0, 'ok');
    }

    public function index(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = ClaimProject::query();

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        if ($request->has('keywords')) {
            $query->where('name', 'like', '%' .$request->get('keywords'). '%');
        }

        if ($request->has('ids')) {
            $ids = explode(',', $request->get('ids'));
            $query->whereIn('id', $ids);
        }

        //列表按id倒排
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');
        $asExcel = $request->get("asExcel", false);
        $info = null;
        if($asExcel){
            // 保持和分页的结构一致，设置data=>{}
            $tmp = $query->get()->toArray();
            $info = array(
                'data' => $tmp
            );
        }else {
            $info = $query->paginate($perPage)->toArray();
        }

        $ids = array_map(function($item) {
            return $item['id'];
        }, $info['data']);


        $applies = DB::table('user_claim_project')
            ->select(DB::raw('count(*) as apply_count, project_id'))
            ->whereIn('project_id', $ids)
            ->groupBy('project_id')
            ->get();

        $applyMap = [];
        foreach ($applies as $apply) {
            $applyMap[$apply->project_id] = $apply;
        }

        foreach ($info['data'] as &$item) {
            if (isset($applyMap[$item['id']])) {
                $item['apply_count'] = $applyMap[$item['id']]->apply_count;
            } else {
                $item['apply_count'] = 0;
            }
        }

        if ($asExcel){
            return Excel::create(time(),function($excel) use ($info){

                $excel->sheet('认领列表', function($sheet) use ($info){

                    $sheet->appendRow(1, array(
                        '项目名称	', '项目发起日期', '认领截止日期', '认领人数'
                    ));

                    for ($i = 0;$i<count($info['data']);$i++){
                        $item = $info['data'][$i];
                        $end = new Carbon();
                        $end->setTimestamp($item['end']);

//                        print_r($tmp);
                        $sheet->appendRow($i+2,array(
                            $item['name'],
                            $item['created_at'],
                            $end->toDateString(),
                            $item['apply_count']
                        ));
                    }
                });
            })->export('xls');
        }


//        Log::info($info);

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function store(Request $request) {
        if ($request->has('id')) {
            return $this->update($request, $request->get('id'));
        }

        $user = $request->user();

        $this->validate($request, [
            'org_id' => $user->type == 4 ? 'required' : '',
            'team_name' => 'required|max:255',
            'logo' => 'max:1024',
            'cover' => 'max:1024',
            'banner' => 'max:1024',
            'name' => 'required|max:255',
            'address' => 'required|max:255',
            'begin' => 'required',
            'end' => 'required|not_before:begin',
            'publish_time' => 'required',
            'content' => 'required'
        ]);

        $node = new ClaimProject();
        $data = $request->only([
            'team_name',
            'org_id',
            'logo',
            'name',
            'address',
            'begin',
            'end',
            'cover',
            'banner',
            'content',
            'status'
        ]);

        $data = $this->rmNullProps($data);


        // default values;
        if ($user->type == 3) {
            $data['org_id'] = $user->org_id;
        }

        if (isset($data['status']) && $data['status'] && empty($data['publish_time'])) {
            $data['publish_time'] = (new Carbon())->getTimestamp();
        }

        $node->fill($data);

        if ($node->save()) {
            $node->load('org');
            $data = $node->toArray();

            return $this->returnJSON($data, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id) {
        $node = ClaimProject::findOrFail($id);

        $user = $request->user();
        $this->validate($request, [
            'org_id' => $user->type == 4 ? 'required' : '',
            'team_name' => 'required|max:255',
            'name' => 'required|max:255',
            'address' => 'required|max:255',
            'begin' => 'required',
            'end' => 'required|not_before:begin',
            'content' => 'required',
            'logo' => 'max:1024',
            'cover' => 'max:1024',
            'banner' => 'max:1024',
        ]);

        $data = $request->only([
            'team_name',
//            'org_id',
            'logo',
            'name',
            'address',
            'begin',
            'end',
            'cover',
            'banner',
            'publish_time',
            'content',
            'status'
        ]);
        $data = $this->rmNullProps($data);

        if (isset($data['status']) && $data['status'] == 1 && $node->status != 1 && empty($data['publish_time'])) {
            $data['publish_time'] = (new Carbon())->getTimestamp();
        }

        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }


    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = ClaimProject::whereIn('id',  $ids)->update(['status' => 1, 'publish_time' => new Carbon()]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '上架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = ClaimProject::whereIn('id',  $ids)->update(['status' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '下架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function destroy(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (ClaimProject::whereRaw('id IN (?)', [$ids])->delete()) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }
}
